const Router = require("koa-router")
const axios = require('axios')
const fs = require('fs')
const WXBizDataCrypt = require("../utils/WXBizDataCrypt")
const {successRender, errorRender, paginationFilter} = require('../utils/utils')
const {addToken, proving} = require('../utils/token')
const Admin = require('../model/Admin')
const User = require('../model/User')
const router = new Router()

//全局接口参数
const secret = '6df3aaff13d2e8c9397beff1237de140'
const appId = 'wx3c21da0a87507160'
const grant_type = 'authorization_code'

//小程序端用户
// 登录
router.post('/mLogin', async ctx => {
  let {js_code, encryptedData, iv, userInfo} = ctx.request.body
  const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${js_code}&grant_type=authorization_code`
  let res = await axios({url: url})
  const body = res.data
  userInfo.openId = body.openid
  const isUser = await User.find({openId: body.openid})
  if (isUser.length === 0) await new User(userInfo).save()
  let token = addToken({id: body.openid})
  ctx.body = successRender({msg: '登录成功', data: {token}})
})

//查询用户信息
router.get('/getUserInfo', async ctx => {
  const token = ctx.request.header.token
  const openId = proving(token).id
  if (openId) {
    const res = await User.find({openId})
    ctx.body = successRender({data: res[0]})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//修改密码
router.post('/mEditPassword', async ctx => {
  const token = ctx.request.header.token
  const openId = proving(token).id
  if (openId) {
    const res = await User.find({openId})
    const {oldPw, newPw} = ctx.request.body
    const oldPassword = res[0].password
    if (oldPassword != oldPw) return ctx.body = errorRender({msg: '旧密码错误'})
    if (newPw.length != 6) return ctx.body = errorRender({msg: '密码长度应为6位数'})
    await User.updateOne({openId}, {password: newPw})
    ctx.body = successRender({data: res[0], msg: '修改成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//web端用户
//管理员登录
router.post('/login', async ctx => {
  const adminInfo = ctx.request.body
  const res = await Admin.find({userName: adminInfo.userName})
  const code = adminInfo.verifyCode.toLowerCase()
  if (code !== ctx.session.picCode) return ctx.body = errorRender({msg: '验证码不正确'})
  if (res.length === 0) return ctx.body = errorRender({msg: '用户名不存在'})
  if (adminInfo.password !== res[0].password) return ctx.body = errorRender({msg: '账户密码错误'})
  const token = addToken({id: res[0]._id})
  ctx.response.headers['Access-Control-Allow-Origin'] = '*'
  ctx.body = successRender({msg: '登录成功', data: {token}})
})

//添加管理员
router.post('/addAdmin', async ctx => {
  const adminInfo = ctx.request.body
  const res = await new Admin(adminInfo).save()
  ctx.body = successRender({msg: '添加成功'})
})

//查询用户列表
router.get('/getUser', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  const keyWord = ctx.request.query.keyWord
  const reg = new RegExp(keyWord, 'i')
  if (userId) {
    let res
    if (keyWord) res = await User.find({$or: [{userName: {$regex: reg}}]})
    else res = await User.find()
    const data = paginationFilter(res, ctx.request.query)
    ctx.body = successRender({data})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//查询管理员列表
router.get('/getAdmin', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  const keyWord = ctx.request.query.keyWord
  const reg = new RegExp(keyWord, 'i')
  if (userId) {
    let res
    if (keyWord) res = await Admin.find({$or: [{userName: {$regex: reg}}]})
    else res = await Admin.find()
    const data = paginationFilter(res, ctx.request.query)
    ctx.body = successRender({data})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//查询用户详情
router.get('/getUserDetails', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const _id = ctx.request.query.id
    const res = await User.findById(_id)
    ctx.body = successRender({data: res})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//查询管理员详情
router.get('/getAdminDetails', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const _id = ctx.request.query.id
    const res = await Admin.findById(_id)
    ctx.body = successRender({data: res})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//个人资料
router.get('/getPersonalInfo', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const res = await Admin.findById(userId)
    ctx.body = successRender({data: res})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//修改用户信息
router.post('/editUser', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const id = ctx.request.body._id
    const userInfo = ctx.request.body
    const res = await User.findByIdAndUpdate(id, userInfo)
    ctx.body = successRender({msg: '修改成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//修改管理员信息
router.post('/editAdmin', async ctx => {
  const token = ctx.request.header.token
  const userId = proving(token).id
  if (userId) {
    const id = ctx.request.body._id
    const userInfo = ctx.request.body
    const res = await Admin.findByIdAndUpdate(id, userInfo)
    ctx.body = successRender({msg: '修改成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//删除管理员
router.get('/removeAdmin', async ctx => {
  const token = ctx.request.header.token
  const _id = ctx.request.query.id
  const userId = proving(token).id
  if (userId) {
    const res = await Admin.findOneAndRemove({_id})
    ctx.body = successRender({msg: '删除成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

//修改密码
router.post('/editPassword', async ctx => {
  const token = ctx.request.header.token
  const _id = ctx.request.body._id
  const oddPassword = ctx.request.body.oddPassword
  const adminInfo = await Admin.findById(_id)
  const userId = proving(token).id
  if (userId) {
    if (adminInfo.password !== oddPassword) return ctx.body = errorRender({msg: '旧密码错误'})
    const res = await Admin.findByIdAndUpdate(_id, ctx.request.body)
    ctx.body = successRender({msg: '修改成功'})
  } else {
    ctx.body = errorRender({msg: '没有访问权限'})
  }
})

module.exports = router
